<?php

namespace app\admin\controller;

use app\admin\model\Admin;
use think\Controller;
use think\facade\Session;
use think\Request;

class Home extends Controller
{
    //检查session防止未登录进入首页
    public function initialize(){
        if(!Session::has('admin')){
            return $this->redirect('admin/Index/login');
        }
    }

    //后台首页
    public function index(){
        //用户基本信息模板赋值
        $this->assign([
            'username' => Session::get('admin')['username'],
            'nickname' => Session::get('admin')['nickname'],
            'email'    => Session::get('admin')['email'],
            'ip'       => Session::get('admin')['ip'],
            'is_super' => Session::get('admin')['is_super'],
        ]);
        return $this->fetch();
    }

    //注销
    public function loginout(){
        Session::delete('admin');
        if (Session::has('admin')){
            return json(['code'=>0,'msg'=>'注销失败']);
        }
        return json(['code'=>1,'msg'=>'注销成功','url'=>'login']);
    }

    //修改密码
    public function password(Request $request){
        if ($request->isPost()){
            $data = [
                'password' => $request->post('password'),
                'confirm'  => $request->post('confirm')
            ];
            $model = new Admin;
            $result = $model->password($data);
            if ($result==1){
                Session::delete('admin');
                return json(['code'=>1,'msg'=>'密码修改成功','url'=>'login']);
            }else{
                return json(['code'=>0,'msg'=>$result]);
            }
        }
//        return $this->fetch();
    }

    //查看日志
    public function log(){
        $list = readLog(Session::get('admin')['username']);
        $this->assign([
            'nickname' => Session::get('admin')['nickname'],
            'email'    => Session::get('admin')['email'],
            'list'     => $list
        ]);
        $html = $this->fetch();
        return json(['html'=>$html]);
    }


}

